package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.*;

class KthLargestSumInABinaryTree {
    // 2024-02-23 14:51:51
    public static void main(String[] args) {
        Solution solution = new KthLargestSumInABinaryTree().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        /**
         * 二叉树在层序遍历中求和
         */
        public long kthLargestLevelSum(TreeNode root, int k) {
            if (root == null) return -1;

            List<Long> sumList = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                long sum = 0;
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.poll();
                    sum += node.val;
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }
                sumList.add(sum);
            }
            if (sumList.size() < k) {
                return -1;
            }
            Collections.sort(sumList);
            return sumList.get(sumList.size() - k);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}